<?php

	include_once("$config[webroot]/includes/page_utf_class.php");
	include_once($config['webroot']."/module/activity/includes/plugin_coupons_class.php");

	if($_GET['operation']=="add" or $_GET['operation']=="edit")
	{
		if($_POST['act'])
		{	
			unset($_GET['s']);
			unset($_GET['m']);
			unset($_GET['operation']);
			//添加优惠券
			//0通用 1唯一 2兑换 3 领取 4 触发 5分享
			if (in_array($_POST['type'], array(0,1,3))){
			    $_POST['stime'].=(' '.$_POST['startHour'].':'.$_POST['startMinute'].':00');
			    $_POST['etime'].=(' '.$_POST['endHour'].':'.$_POST['endMinute'].':00');
			    $_POST['stime']= strtotime($_POST['stime']);
			    $_POST['etime']= strtotime($_POST['etime']);
			}else{
			    $_POST['stime']=$_POST['sday'];
			    $_POST['etime']=$_POST['eday'];
			}
			if (empty($_POST['stime'])){
			    $_POST['stime']=0;
			}elseif (empty($_POST['etime'])){
			    $_POST['etime']=7;
			}
			if(!in_array($_POST['type'], array(2))){
			    $_POST['cost_points']=0;
			}elseif(empty($_POST['cost_points'])){
			    $_POST['cost_points']=1000;
			}
			 $_POST['per_type']=$_POST['per_type_'.$_POST['type']];
			
			if($_POST["act"]=='save')
			{
				$coupons=new coupons();
				$coupons->add_coupons();
			}
			//修改优惠券
			if($_POST["act"]=='edit' and is_numeric($_POST['id']))
			{
				$coupons=new coupons();
				$coupons->edit_coupons();
				unset($_GET['editid']);
			}
			$getstr=implode('&',convert($_GET));
			msg("?m=activity&s=coupons.php&$getstr");
		}
		//优惠券信息
		if($_GET['editid'] and is_numeric($_GET['editid']))
		{
			$sql="select * from ".COUPONS." where id='$_GET[editid]'";
			$db->query($sql);
			$de=$db->fetchRow();
			//var_dump($de);
			
		}else{
		    $de['start_time']=strtotime(date('Y-m-d'))+86400;
		    $de['end_time']=strtotime("+1 month",$de['start_time']);
		    $de['type']=1;
		}
    	$sql="select * from ".PCAT." where catid<9999 order by displayorder,catid";
    	$db->query($sql);
    	$de['cat']=$db->getRows();
    	foreach($de['cat'] as $key=>$val)
    	{
    	    $sql="select * from ".PCAT." where catid < '".$val['catid']."99' and catid > '".$val['catid']."00' order by displayorder,catid";
    	    $db->query($sql);
    	    $a=$db->getRows();
    	    foreach($a as $ke=>$va)
    	    {
    	        $sql="select * from ".PCAT." where catid < '".$va['catid']."99' and catid > '".$va['catid']."00' order by displayorder,catid";
    	        $db->query($sql);
    	        $a[$ke]['scat']=$db->getRows();
    	    }
    	    $de['cat'][$key]['scat']=$a;
    	}
    	
    	if ($de['except']){
    	$sql="SELECT id,pic,pname,price,market_price,cost_price,sku as code,stock as amount FROM ".SETMEAL." where id in(".trim($de['except'],',').") and statu>-3 order by id desc";
    	$db->query($sql);
    	$de['products']=$db->getRows();
    	}
    	
	}
	
	elseif ($_GET['operation']=="make"){//生成优惠券
	    if (empty($_POST['cpns_id'])){
	        echo 'id错误';
	        die;
	        
	    }elseif (empty($_POST['cpns_nums'])||$_POST['cpns_nums']<=0||!is_numeric($_POST['cpns_nums'])){
	        echo '数量错误';
	        die;
	    }
	    else{
	        $sql="select * from ".COUPONS." where id='{$_POST['cpns_id']}'";
	        $db->query($sql);
	        $de=$db->fetchRow();
	        if (empty($de)){
	            echo '优惠券不存在';
	            die;
	        }
	        $coupons=new coupons();
	         $pwds=$coupons->get_coupons_pwd($_POST['cpns_nums'],$de['type'],$de['id'],$_POST['make_type'],$de['cpns_make_nums']);
	        
	         if($coupons->make_coupons($de, $pwds)){
	             echo '1';
	         }
	        //var_dump($pwds);
	        exit;
	        
	    }
	    
	    
	}
	
	elseif ($_GET['operation']=="bind"){//绑定优惠券
	    if (empty($_POST['cpns_key'])){
	        echo 'id错误';
	        die;
	         
	    }
	    else{
	        $sql="select userid,username from ".MEMBER." WHERE userid='$_POST[uname]'";
	        $db->query($sql);
	        $buid=$db->fetchField('userid');
	        if (empty($buid)){
	        		$sql ="select userid,username from ".MEMBER. " WHERE username ='$_POST[uname]'";
	        		$db->query($sql);
	        		$buid=$db->fetchField('userid');
	        		if (empty($buid)){
	            	echo '用户不存在';
	            	die;
	        		}
	        }else{
	        	$_POST[uname]=$db->fetchField('username');
	        }
	        $coupons=new coupons();
	        $bind_info=$coupons->bind_coupons($_POST['cpns_key'],$buid,$_POST[uname]);
	         
	        if ($bind_info==1){
	            echo '1';
	        }else{
	            echo $bind_info;
	        }
	        //var_dump($pwds);
	        exit;
	         
	    }
	}
	
	elseif ($_GET['operation']=="bindall"){//批量绑定优惠券
		if (empty($_POST['cpns_id'])){
			echo 'id错误';
			die;
		}
		else{
			$buids= explode(',',$_POST['uids']);
			$bind_nums=count($buids);
			if ($bind_nums>1000){
				echo '绑定数量太多';
				die;
			}
			$buids = array_unique($buids);
			$true_bind_nums = count($buids);
			
			$t=time();
			$sql="select cpns_key from ".COUPONSUSERS." where status='1' and type='1' and end_time>{$t} and cpns_id=".$_POST['cpns_id']." limit ".$true_bind_nums;
			$db->query($sql);
			$coupons_info=$db->getRows();
			if (empty($coupons_info)){
				echo '没有可以绑定的优惠券,过期或者优惠券类型不可绑定';
				die;
			}elseif(count($coupons_info)<$true_bind_nums){
				echo '优惠券数量不够，请增加数量';
				die;
			}
			$coupons=new coupons();
			$bind_ok_nums=0;
			foreach($buids as $key=> $buid){
				
				$sql="select userid from ".MEMBER." WHERE userid='$buid'";
				$db->query($sql);
				if(!$db->fetchField('userid')){
					$no_users[]=$buid;
				}else{
					$bind_info=$coupons->bind_coupons($coupons_info[$key]['cpns_key'],$buid);
					if ($bind_info==1){
						$bind_ok_nums++;
					}else{
						$bind_error[]=$buid;
					}
				}
			}
			if($bind_ok_nums==$true_bind_nums){
				echo '1';
			}elseif ($bind_error||$no_users){
				echo "2";
				if ($no_users){
					echo implode(',',$no_users).'用户不存在';
				}
				if ($bind_error){
					echo implode(',',$bind_error).'绑定失败';
				}
			}
			exit;
	
		}
	}
	
	elseif ($_GET['operation']=="send"||$_POST['operation']=='send'){//发放
	    $coupons=new coupons();
	    if($_GET['delid'])
	    {
	        $coupons->send_coupons($_GET['delid'],$_GET['cpns_id']);
	    }elseif (is_array($_POST['chk'])){
	        $coupons->send_coupons($_POST['chk'],$_GET['cpns_id']);
	    }
	    msg("?m=activity&s=coupons.php&operation=users&cpns_id=".$_GET['cpns_id'].'&page_size='.$_GET['page_size']);
	     
	    
	}
	elseif ($_GET['operation']=="forbid"||$_POST['operation']=='forbid'){//禁用
	    $coupons=new coupons();
	     
	    if($_GET['delid'])
	    {
	        $coupons->forbid_coupons($_GET['delid'],$_GET['cpns_id']);
	    }
	    

	        if(is_array($_POST['chk']))
	        {
	          $coupons->forbid_coupons($_POST['chk'],$_GET['cpns_id']);
	            
	        }
	    msg("?m=activity&s=coupons.php&operation=users&cpns_id=".$_GET['cpns_id'].'&page_size='.$_GET['page_size']);
	     
	}
	
	
	elseif ($_GET['operation']=="users" || $_POST['act']=='export'){//已生成优惠券


	    //获取优惠券
	    $sql="select * from ".COUPONSUSERS;
	    
	        if ($_GET['cpns_id']){
	            $sql.=" where cpns_id=".$_GET['cpns_id'];
	        }
	        if ($_GET['page_size']){
	        	$page_size=$_GET['page_size'];
	        }else{
	        	$_GET['page_size']=$page_size=100;
	        }

	            
	    $sql.=" order by id desc";
	    $db->query($sql);
	    $totalRows = $db->num_rows();
	    
	    if ($_POST['act']=='export'){
	    	include_once '../lib/php_excel.php';
	    	$sql="select title,cpns_if,cpns_then,FROM_UNIXTIME(start_time, '%Y-%m-%d %H:%i:%s' )as start_time,FROM_UNIXTIME(end_time, '%Y-%m-%d %H:%i:%s' )as end_time,cpns_key,catid,status,uname,order_id from ".COUPONSUSERS;
	    	 
	    	if ($_GET['cpns_id']){
	    		$sql.=" where cpns_id=".$_GET['cpns_id'];
	    	}
	    	$sql.=" order by id desc";
	    	$db->query($sql);
	    	$export_data=$db->getRows();
	    	
	    	foreach ($export_data as $key=> $var)
	    	{
	    		$export_data[$key]['cpns_if']='满'.$export_data[$key]['cpns_if'].'减'.$export_data[$key]['cpns_then'];
	    		$export_data[$key]['cpns_then']=$export_data[$key]['start_time'].'-'.$export_data[$key]['end_time'];
	    		$export_data[$key]['start_time']=$export_data[$key]['cpns_key'];
	    		if($export_data[$key]['catid'] == '0')
	    		{
	    			$export_data[$key]['end_time']='全分类';
	    		}
	    		
	    		
	    		if($export_data[$key]['status'] == '0')
	    		{
	    			$export_data[$key]['cpns_key'] = '已生成';
	    		}else if($export_data[$key]['status'] == '1')
	    		{
	    			$export_data[$key]['cpns_key'] = '已发放';
	    		}else if($export_data[$key]['status'] == '2')
	    		{
	    			$export_data[$key]['cpns_key'] = '已绑定';
	    		}else if($export_data[$key]['status'] == '3')
	    		{
	    			$export_data[$key]['cpns_key'] = '已使用';
	    		}else if($export_data[$key]['status'] == '-1')
	    		{
	    			$export_data[$key]['cpns_key'] = '已禁用';
	    		}
	    		$export_data[$key]['catid']=$export_data[$key]['uname'];
	    		$export_data[$key]['status']=$export_data[$key]['order_id'];
	    		$export_data[$key]['uname']='';
	    		$export_data[$key]['order_id']='';
	    	}
	    	$queue[0] = array("名称", "使用规则","起止时间","优惠码","分类","状态","会员","订单");//定义表头
	    	$export_data = array_merge($queue,$export_data);
	    	//print_r($export_data);
	    	$filename =   "优惠券信息" . date ( "YmdHis" );
	    	$xls = new Excel_XML ( 'UTF-8', false, '优惠券信息' );
	    	$xls->addArray ($export_data );
	    	$xls->generateXML ($filename );
	    	exit ();
	    }
	    
	    $page = new Page;
	    $page->listRows=$page_size;
	    //分页
	    if (!$page->__get('totalRows'))
	    {
	        $db->query($sql);
	        $page->totalRows = $db->num_rows();
	    }
	    $sql .= "  limit ".$page->firstRow.",".$page->listRows;
	    $db->query($sql);
	    $de['list']=$db->getRows();
	    if($de['list'])
	    {
	        foreach($de['list'] as $key=>$v)
	        {
	            $tmp=array();
	            if ($v['catid']){
	                $sql = "select cat from ".PCAT." where '$v[catid]' like concat(`catid`,'%')  order by catid asc";
	                $db->query($sql);
	                foreach ($cat=$db->getRows() as $item){
	                    $tmp[]=$item['cat'];
	                }
	            }
	            	
	            $de['list'][$key]['catid']=implode('->', $tmp);
	        }
	    }
	    $de['page']=$page->prompt();
	    
	    $sql="select id,title from ".COUPONS." where status>0  order by id desc";
	    $db->query($sql);
	    $de['cpns']=$db->getRows();
	     
	     
	     
	
	}
	else
	{
		//删除优惠券
		if($_GET['delid'])
		{
		  
		  unset($_GET['m']);
		  unset($_GET['s']);
		  $sql="select 1 from ".COUPONSUSERS."  where cpns_id='$_GET[delid]' and status>0 limit 1";
		  $db->query($sql);
		  if($db->fetchRow()){
		      unset($_GET['delid']);
		      $getstr=implode('&',convert($_GET));
		      msg("?m=activity&s=coupons.php&".$getstr,'此优惠券含有发放或使用的优惠券不可删除');
		  }
			$sql="delete from ".COUPONS."  where id='$_GET[delid]'";
			$db->query($sql);
			$sql="delete from ".COUPONSUSERS."  where cpns_id='$_GET[delid]'";
			$db->query($sql);
			unset($_GET['delid']);
			$getstr=implode('&',convert($_GET));
			msg("?m=activity&s=coupons.php&".$getstr);
		}
		if($_POST['act']=='op')
		{
			if(is_array($_POST['chk']))
			{
				$id=implode(",",$_POST['chk']);
				$sql="delete from ".COUPONS." where id in ($id)";
				$db->query($sql);
				$sql="delete from ".COUPONSUSERS." where cpns_id in ($id)";
				$db->query($sql);
			}
			msg("?m=activity&s=coupons.php");
		}	
		//获取优惠券
		$sql="select * from ".COUPONS."  order by id desc";
		$page = new Page;
		$page->listRows=20;
		//分页
		if (!$page->__get('totalRows'))
		{
			$db->query($sql);
			$page->totalRows = $db->num_rows();
		}
		$sql .= "  limit ".$page->firstRow.",".$page->listRows;
		$db->query($sql);
		$de['list']=$db->getRows();
		if($de['list'])
		{
			foreach($de['list'] as $key=>$v)
			{
				$tmp=array();
				if ($v['catid']){
					$sql = "select cat from ".PCAT." where '$v[catid]' like concat(`catid`,'%')  order by catid asc";
					$db->query($sql);
					foreach ($cat=$db->getRows() as $item){
						$tmp[]=$item['cat'];
					}
				}
				 
				$de['list'][$key]['catid']=implode('->', $tmp);
			}
		}
		$de['page']=$page->prompt();
	}
	$tpl->assign("de",$de);
	$tpl->assign("countpro",$totalRows);
	$tpl->assign("config",$config);
	$tpl->display("coupons.htm");

?>